package com.puris.servlet.student;

import com.puris.service.student.Service;
import com.puris.service.student.ServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author Sonata
 * @data 2021/11/22 18:07
 */
public class JoinCompetitionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String studentId = (String) req.getSession().getAttribute("id");
        String competitionId = req.getParameter("competitionId");

        Service service = new ServiceImpl();

        String competitionName = null;
        try {
            competitionName = service.joinCompetition(studentId, competitionId);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        if (competitionName != null) {
            req.setAttribute("success", "报名成功！");
            req.getSession().setAttribute("competitionName", competitionName);
        } else {
            req.setAttribute("error", "报名失败！请确保编号正确，且每人只能报名一种比赛！");
        }
        req.getRequestDispatcher("jsp/student/joinCompetition.jsp").forward(req, resp);
    }
}
